//
//  OAuthViewController.swift
//  weibo
//
//  Created by cmh on 15/9/2.
//  Copyright © 2015年 cmh. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController, UIWebViewDelegate {
    
    private lazy var webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 加载网页
        webView.loadRequest(NSURLRequest(URL: NetWrokTools.shareTools.oauthUrl))
        
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self
        
        // 标题
        title = "登陆"
        
        // nav左右两边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "setUserIdAndPasswd")
        
    }
    
    // 关闭页面
    @objc private func close() {
    
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    // 自动填充账号和密码
    @objc private func setUserIdAndPasswd() {
        
        // 自动填充的账号和密码
        let js = "document.getElementById('userId').value = '13501826753';" + "document.getElementById('passwd').value = '888888cmh';"
        
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    }
    
    // 加载网页前后添加加载小动画
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    // 检测回调的地址
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        // 网页地址
        let urlString = request.URL!.absoluteString

        // 如果不包括回调地址就继续
        if !urlString.hasPrefix(NetWrokTools.shareTools.redirect_uri) {
            
            return true
            
        }
        
        // 如果包括回调地址，检测？之后的字符串中是否包含“code=”
        if let query = request.URL!.query where query.hasPrefix("code=") {
        
            let code = query.substringFromIndex("code=".endIndex)
            
            // 访问网络
            UserAccountViewModel.shareUserAccount.loadUserAccount(code).subscribeError({ (error) -> Void in
                
                printLog(error)
                
                }, completed: { () -> Void in
                    printLog("登陆成功")
                    
                    // 关闭控制器
                    SVProgressHUD.dismiss()
                    self.dismissViewControllerAnimated(true, completion: { () -> Void in
                        
                        // 发送切换控制器的通知
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewContrillerNotification, object: "welcome")
                    })
            })

        }else{
            
            printLog("取消授权")
        
        }
        
        return false
        
    }

}
